import editForm from "../form.vue";
import userEditForm from "../distributionUserForm.vue";
import menuEditForm from "../distributionMenuForm.vue";
import { message } from "@/utils/message";
import {
  distributionUser,
  distributionMenu,
  getMenuListByRoleId,
  getUserListByRoleId,
  deleteRole,
  updateRole,
  addRole,
  getRoleList
} from "@/api/role";
import { getUserList } from "@/api/user";
import { addDialog } from "@/components/ReDialog";
import { ref, onMounted, h } from "vue";
import { type FormItemProps } from "../utils/types";
import { commonStatusColorEnum, commonStatusEnum } from "@/enums/enum";
import { getTableMenuList } from "@/api/menu";

export function useRole() {
  const formRef = ref();
  const dataList = ref([]);
  const loading = ref(true);

  interface Option {
    key: number;
    label: string;
    initial: string;
  }
  // const { tagStyle } = usePublicHooks();

  const columns: TableColumnList = [
    {
      type: "selection",
      align: "left"
    },
    {
      label: "序号",
      type: "index",
      width: 70
    },
    {
      label: "名字",
      prop: "name"
      // align: "left"
    },
    {
      label: "标识",
      prop: "roleKey",
      minWidth: 70
    },
    {
      label: "描述",
      prop: "remark",
      minWidth: 70
    },
    {
      label: "状态",
      prop: "houseStatus",
      minWidth: 100,
      cellRenderer: ({ row, props }) => (
        <el-tag size={props.size} type={commonStatusColorEnum[row.status]}>
          {commonStatusEnum[row.status]}
        </el-tag>
      )
    },
    {
      label: "操作",
      fixed: "right",
      width: 380,
      slot: "operation"
    }
  ];

  async function onSearch() {
    loading.value = true;
    const { data } = await getRoleList();

    dataList.value = data;

    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  function openDialog(title = "新增", row?: FormItemProps) {
    addDialog({
      title: `${title}角色`,
      props: {
        formInline: {
          id: row?.id ?? null,
          name: row?.name ?? "",
          roleKey: row?.roleKey ?? "",
          status: row?.status ?? 0,
          remark: row?.remark ?? ""
        }
      },
      width: "40%",
      draggable: true,
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        // const pathUrl = formRef.value.pathUrl;
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(`您${title}了资产拥有人为${curData.name}的这条数据`, {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(async valid => {
          if (valid) {
            console.log("curData", curData);
            // 表单规则校验通过
            if (title === "新增") {
              // console.log(curData, "--");
              // 实际开发先调用新增接口，再进行下面操作
              const res = await addRole(curData);
              console.log(res);
              chores();
            } else {
              // curData.imageUrl = pathUrl;
              // 实际开发先调用编辑接口，再进行下面操作
              const res = await updateRole(curData);

              if (res.code === 200) {
                if (res.code == 201) {
                  message(`更新失败`, {
                    type: "error"
                  });
                } else {
                  chores();
                }
              }
            }
          }
        });
      }
    });
  }

  async function handleDelete(row) {
    console.log(row.id);
    const { data } = await deleteRole({ ids: [row.id] });
    console.log(data);
    message(`您删除了名称为${row.name}的这条数据`, { type: "success" });
    onSearch();
  }

  /**
   * 未分配用户数据格式处理
   * @param value
   * @returns
   */
  const generateData = (value: Array<any>) => {
    const data: Option[] = [];
    value.forEach(city => {
      data.push({
        label: city.nickName,
        key: city.id,
        initial: city.nickName
      });
    });
    return data;
  };

  const noDistributionUserList = ref([]);
  const distributionUserList = ref([]);

  async function distributionUserHandel(row) {
    const res1 = await getUserListByRoleId({ roleId: row.id });
    const res2 = await getUserList({ currentPage: 1, pageSize: 100000 });
    distributionUserList.value = res1.data;
    noDistributionUserList.value = generateData(res2.data.records);

    addDialog({
      title: `分配用户`,
      props: {
        formInline: {
          noDistributionUser: noDistributionUserList.value,
          distributionUser: distributionUserList.value
        }
      },
      width: "50%",
      draggable: true,
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(userEditForm, { ref: formRef }),
      beforeSure: async (done, { options }) => {
        // const FormRef = formRef.value.getRef();
        // const pathUrl = formRef.value.pathUrl;
        const curData = options.props.formInline;
        console.log(curData);
        await distributionUser({
          roleId: row.id,
          userIds: curData.distributionUser
        });
        message(`分配成功`, {
          type: "success"
        });
        done(); // 关闭弹框
      }
    });
  }

  const distributionMenuList = ref([]);
  const readyDistributionMenuList = ref([]);
  async function distributionMenuHandel(row) {
    const res1 = await getTableMenuList();
    const res2 = await getMenuListByRoleId({ roleId: row.id });

    distributionMenuList.value = res1.data;
    readyDistributionMenuList.value = res2.data;

    addDialog({
      title: `分配权限`,
      props: {
        formInline: {
          distributionMenuList: distributionMenuList.value,
          readyDistributionMenuList: readyDistributionMenuList.value
        }
      },
      width: "50%",
      draggable: true,
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(menuEditForm, { ref: formRef }),
      beforeSure: async done => {
        const FormRef = formRef.value.getRef();

        const selectKeys = FormRef.getCheckedKeys().concat(
          FormRef.getHalfCheckedKeys()
        );

        await distributionMenu({
          roleId: row.id,
          menuIds: selectKeys
        });

        message(`分配成功`, {
          type: "success"
        });
        done(); // 关闭弹框
      }
    });
  }

  onMounted(() => {
    onSearch();
  });

  return {
    loading,
    columns,
    dataList,
    /** 搜索 */
    onSearch,
    /** 新增、编辑部门 */
    openDialog,
    /** 删除部门 */
    handleDelete,
    distributionUserHandel,
    distributionMenuHandel
  };
}
